<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import {Plus, Edit, Delete, UploadFilled, Search, Refresh} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import axios from "axios";
import { usePagination } from "@@/composables/usePagination"
import {
  getBannersList,
  addtBannersList,
  updateBannersList,
  deleteBannersList,
  updateBannersListStatus
} from '@@/apis/topicInfo/banner';

// 接收图片上传URL
const props = defineProps({
  uploadUrl: {
    type: String,
    required: true
  }
});

// 轮播图数据
const carousels = ref([]);
const carouselDialogVisible = ref(false);
const carouselDialogTitle = ref('添加轮播图');
const currentCarousel = reactive({
  title: '',
  description: '',
  imageUrl: ''
});
const carouselFormRef = ref(null);
const carouselRules = ref({
  imageUrl: [
    { required: true, message: '请上传图片', trigger: 'blur' }
  ]
});

const vFileList = ref([]);

const formData = reactive({
  description: "",
  status: ""
});
const searchFormRef = ref(null);

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 查询数据
function handleSearch() {
  getBannersListAPI(formData);
}

// 重置表单
function resetSearch() {
  searchFormRef.value?.resetFields();
  handleSearch();
}

// 获取轮播图
function getBannersListAPI() {
  const formdata = new FormData();
  formdata.append('description', formData.description);
  formdata.append('status', formData.status);
  formdata.append('page', paginationData.currentPage);
  formdata.append('size', paginationData.pageSize);

  getBannersList(formData).then(res => {
    if(res.code === 200) {
      carousels.value = res.data.records;
      paginationData.total = res.data.total;
      // console.log('carousels', carousels);
    }
  })
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getBannersListAPI, { immediate: true })

// 初始化数据
onMounted(() => {
  // 模拟轮播图数据
  // carousels.value = [
  //   {
  //     id: 1,
  //     title: '首页轮播图1',
  //     description: '这是首页的第一张轮播图，展示最新活动信息',
  //     imageUrl: 'https://picsum.photos/id/1/1200/400'
  //   },
  //   {
  //     id: 2,
  //     title: '首页轮播图2',
  //     description: '这是首页的第二张轮播图，展示产品特色',
  //     imageUrl: 'https://picsum.photos/id/2/1200/400'
  //   }
  // ];
});

// 图片上传组件改变的处理函数
const handleFileChange = (file, fileList) => {
  console.log('file', file);
  console.log('fileList', fileList);
  // 验证文件类型
  const isJpgOrPng = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片');
    return false;
  }

  // 验证文件大小
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB');
    return false;
  }

  if (file.status === 'ready') {
    // 创建 FileReader 实例，用于读取本地文件
    const reader = new FileReader();
    // 读取文件为 dataURL（Base64 格式）
    reader.readAsDataURL(file.raw);
    // 读取完成后触发
    reader.onload = (e) => {
      // 将读取到的 dataURL 赋值给文件对象的 url 属性（用于显示）
      currentCarousel.imageUrl = e.target.result;
      // 更新文件列表
      vFileList.value = [fileList[fileList.length - 1]];
      console.log('vFileList',  vFileList);
    }
  }
}

// 轮播图操作
const handleAddCarousel = () => {
  carouselDialogTitle.value = '添加轮播图';
  currentCarousel.id = null;
  currentCarousel.title = '';
  currentCarousel.description = '';
  currentCarousel.imageUrl = '';
  carouselDialogVisible.value = true;
};

const handleEditCarousel = (row) => {
  carouselDialogTitle.value = '编辑轮播图';
  currentCarousel.id = row.id;
  currentCarousel.title = row.title;
  currentCarousel.displayOrder = row.displayOrder;
  currentCarousel.description = row.description;
  currentCarousel.imageUrl = row.imageUrl;
  carouselDialogVisible.value = true;
};

const handleEditStatus = (row, status) => {
  const formData = new FormData();
  formData.append("id", row.id);
  if(status === '0') {
    formData.append("status", '0');
  }else {
    formData.append("status", '1');
  }

  updateBannersListStatus(formData).then(res => {
    // console.log('修改轮播图列表的结果是--->', res);
    if(res.code === 200) {
      // 重新获取轮播图列表
      getBannersListAPI();
    }
  })

  axios({
    url: "/topicInfo/banner/update",
    method: "post",
    data: formData
  }).then(res => {
    // console.log('修改轮播图列表的结果是--->', res);
    if(res.data.code === 200) {
      // ElMessage.success('轮播图更新成功');
      // 重新获取轮播图列表
      getBannersListAPI();
    }
  })
}

const handleDeleteCarousel = (id) => {
  ElMessageBox.confirm(
    '确定要删除这张轮播图吗？此操作不可撤销。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(() => {
    deleteBannersList(id).then(res => {
      console.log('删除轮播图列表的结果是--->', res);
      if(res.code === 200) {
        ElMessage.success('轮播图删除成功');
        // 重新获取轮播图列表
        getBannersListAPI();
      }
    })
  }).catch(() => {
    // 取消删除
  });
};

// 图片预览处理
const previewVisible = ref(false);
const previewImageUrl = ref('');

const handlePreview = (url) => {
  previewImageUrl.value = url;
  previewVisible.value = true;
};

const handleSaveCarousel = () => {
  carouselFormRef.value.validate((valid) => {
    if (valid) {
      if (currentCarousel.id) {
        // 编辑
        const formData = new FormData();
        formData.append("id", currentCarousel.id);
        formData.append("displayOrder", currentCarousel.displayOrder);
        formData.append("description", currentCarousel.description);
        formData.append("image", vFileList.value[0].raw);

        updateBannersList(formData).then(res => {
          console.log('修改轮播图列表的结果是--->', res);
          if(res.code === 200) {
            ElMessage.success('轮播图更新成功');
            // 重新获取轮播图列表
            getBannersListAPI();
          }
        })
      } else {
        // 添加
        const formData = new FormData();
        formData.append("displayOrder", carousels.value.length + 1);
        formData.append("description", currentCarousel.description);
        formData.append("image", vFileList.value[0].raw);
        // console.log('vFileList.value[0]', vFileList.value[0].raw);
        // console.log(formData.get('image'));
        // return;

        addtBannersList(formData).then(res => {
          console.log('添加轮播图列表的结果是--->', res);
          if(res.code === 200) {
            ElMessage.success('轮播图添加成功');
            // 重新获取轮播图列表
            getBannersListAPI();
          }
        })
      }
      carouselDialogVisible.value = false;
    }
  });
};
</script>

<template>
  <div class="tab-pane">
    <div class="pane-header">
      <el-card>
        <el-form
          :model="formData"
          label-position="left"
          class="search-form"
          ref="searchFormRef"
          :inline="true"
        >
          <el-form-item prop="description" label="描述">
            <el-input v-model="formData.description" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="status" label="状态">
            <el-select
              v-model="formData.status"
              style="width: 240px"
            >
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">
              查询
            </el-button>
            <el-button :icon="Refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card>
      <el-button
        type="primary"
        :icon="Plus"
        @click="handleAddCarousel"
      >
        添加轮播图
      </el-button>
<!--      <el-button type="danger" :icon="Delete">-->
<!--        批量删除-->
<!--      </el-button>-->
      <el-table
        :data="carousels"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="imageUrl"
          label="图片"
          align="center"
        >
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              style="width: 100px; height: 60px; object-fit: cover"
              fit="cover"
              @click="handlePreview(scope.row.imageUrl)"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="description"
          label="状态"
          align="center"
        >
          <template #default="scope">
            <el-tag @click="handleEditStatus(scope.row, '0')" v-if="scope.row.status === '1'" type="success" effect="plain" disable-transitions>
              启用
            </el-tag>
            <el-tag @click="handleEditStatus(scope.row, '1')" v-else type="danger" effect="plain" disable-transitions>
              禁用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              bg
              text
              size="small"
              @click="handleEditCarousel(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              bg
              text
              size="small"
              @click="handleDeleteCarousel(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 轮播图表单弹窗 -->
    <el-dialog
      v-model="carouselDialogVisible"
      :title="carouselDialogTitle"
      width="500px"
    >
      <el-form
        :model="currentCarousel"
        ref="carouselFormRef"
        :rules="carouselRules"
        label-width="100px"
      >
        <el-form-item label="图片" prop="imageUrl">
          <!-- 图片上传组件 -->
          <el-upload
            class="avatar-uploader"
            v-model:file-list="vFileList"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <el-image
              v-if="currentCarousel.imageUrl"
              :src="currentCarousel.imageUrl"
              style="width: 100%; height: 200px; object-fit: contain; border: 1px dashed #ddd"
              fit="contain"
            ></el-image>
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><upload-filled /></el-icon>
              <div class="upload-text">点击上传图片</div>
              <div class="upload-hint">支持 JPG、PNG 格式，建议尺寸 1200×400</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="currentCarousel.description"
            type="textarea"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="carouselDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleSaveCarousel"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="60%"
      top="5vh"
    >
      <el-image
        :src="previewImageUrl"
        style="width: 100%; height: 70vh; object-fit: contain"
        fit="contain"
      ></el-image>
    </el-dialog>
  </div>
</template>

<style scoped>
.tab-pane {
  height: 100%;
  padding: 20px;
}

.pane-header {
  //display: flex;
  //justify-content: space-between;
  //align-items: center;
  margin-bottom: 20px;
}

.pane-header h2 {
  font-size: 18px;
  color: #34495e;
  font-weight: 600;
}

/* 上传组件样式 */
.upload-placeholder {
  width: 100%;
  height: 200px;
  border: 1px dashed #ddd;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #666;
  cursor: pointer;
  transition: border-color 0.2s;
}

.upload-placeholder:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #999;
}

.upload-text {
  font-size: 14px;
  margin-bottom: 5px;
}

.upload-hint {
  font-size: 12px;
  color: #999;
}

/* Element Plus 组件样式覆盖 */
::v-deep .el-table {
  margin-top: 10px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-textarea__inner {
  resize: vertical;
}

/* 表格图片样式 */
.el-image {
  border-radius: 4px;
  cursor: pointer;
}

.pager-wrapper {
  margin-top: 20px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
}
.el-tag {
  cursor: pointer;
}
</style>
